import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { GlobalService, RequestService } from '../../../../cores/services';
import { PurchaseService } from '../../services/purchase.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Pagination, ConfirmService, ToastService, Item } from 'ng-tui';
import { ApiData, SearchParams } from '../../../../cores/classes';
import { Goods } from '../../interfaces/purchase.interface';
import { skipWhile, map, switchMap } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
    templateUrl: './order-detail.component.html',
    providers: [Location, { provide: LocationStrategy, useClass: PathLocationStrategy }],
})
export class OrderDetailComponent implements OnInit {
    theads = ['#', '订单编号', '采购单位', '采购员', '合同', '订购日期', '到货日期', '供应商名称',
        '采购金额(含税)', '采购金额(未税)', '预入仓库', '运输公司', '收货地址', '审核人', '单据状态', '录入人'];
    billTh = ['#', '明细编号', '产品名称', '条形码', '计量单位', '采购数量', '采购箱数', '含税单价', '含税金额',
        '未税金额', '未税金额', '税率', '保质期(天)', '标准含税单价', '折扣率', '箱条码', '厂家货号', '品牌', '备注'];
    orderTh = ['#', '商品编号', '商品名称', '条形码', '厂家货号', '单位', '口味/颜色', '规格/尺寸', '数量', '箱数', '价格', '金额', '税率', '备注', '箱条码', '品牌', '操作'];

    thSec = ['月份', '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月', '合计'];
    tsSelect = ['Amsterdam', 'Antwerp', 'Athens', 'Barcelona',
        'Berlin', 'Birmingham', 'Bradford', 'Bremen', 'Brussels', 'Bucharest',
        'Budapest', 'Cologne', 'Copenhagen', 'Dortmund', 'Dresden', 'Dublin',
        'Düsseldorf', 'Essen', 'Frankfurt', 'Genoa', 'Glasgow', 'Gothenburg',
        'Hamburg', 'Hannover', 'Helsinki', 'Kraków', 'Leeds', 'Leipzig', 'Lisbon',
        'London', 'Madrid', 'Manchester', 'Marseille', 'Milan', 'Munich', 'Málaga',
        'Naples', 'Palermo', 'Paris', 'Poznań', 'Prague', 'Riga', 'Rome',
        'Rotterdam', 'Seville', 'Sheffield', 'Sofia', 'Stockholm', 'Stuttgart',
        'The Hague', 'Turin', 'Valencia', 'Vienna', 'Vilnius', 'Warsaw', 'Wrocław',
        'Zagreb', 'Zaragoza', 'Łódź'];
    search = new SearchParams({ start: '', end: '' });
    idDetail: any = '';
    list = [];
    orderId: any = '';
    supplierId: any = '';
    loading = false;
    isAddTr = false; // 是否添加新的商品
    isChildSave = false;
    isChange = !this.isChildSave;  // 是否可编辑
    pagination = new Pagination();
    parentTypes = new Array<Item>();
    childTypes = new Array<any>();
    goodsThreeType = new Array<any>();
    goods: Goods = { id: 0, isActive: 1, goodsName: '' };
    newList = {
        orderDate: '', supplierId: '', balance: '', transportCompany: '', estimatedArrivalDate: '', inWarehouseId: '',
        buyerId: '', areaId: '', volume: '', weight: '', applicantId: '', purchaseAmount: '', purchaseBoxAmount: '', amountOfDocuments: '',
        wholeSingleDiscount: '', purchaseMode: '', supplierMobile: '', contractTask: '', annualTiredMining: '',
        goods: []
    };
    newGoods = {
        goodsNumber: '', goodsId: '', barCode: '', manufactorNumber: '', unit: '', flavorColor: '', specificationsDimensions: '',
        amount: '', boxAmount: '', price: '', money: '', taxRate: '', remarks: '', boxBarCode: '', brandId: ''
    };
    listGoods = [];
    supplier = [];
    people = [];
    warehouse = [];
    area = [];
    selectValue = '';
    nick = '';
    isOnly = false;
    searchGoods = (goodsName: string) => {
        // return this.request.withoutHost
        //     .get('https://www.cool1024.com/store/user/search', { limit: 20, offset: 0, nick: key }).pipe(
        //         map<ApiData, Item[]>(res => res.datas.rows.map(row => ({
        //             value: row.id,
        //             text: row.nick,
        //             content: `<img class="rounded-circle mr-2" width="30" src="${row.avatar}">${row.nick}`
        //         })))
        //     );
        return of(goodsName).pipe(
            skipWhile(res => !res),
            switchMap<string, Item[]>(key => this.request.get('/managerapi/goods/list/get', { goodsName: key }).pipe(
                map<ApiData, Item[]>(res => res.datas.map(row => ({
                    value: row,
                    text: row.goodsName,
                })))
            ))
        );
    }

    get getChildTypes(): Item[] {
        return this.childTypes.filter(type => type.parentId === this.goods.goodsParentType);
    }
    get getThreeTypes(): Item[] {
        return this.childTypes.filter(type => type.parentId === this.goods.goodsParentType);
    }
    constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
        private confirm: ConfirmService,
        private toast: ToastService,
        public global: GlobalService,
        private request: RequestService,
        private purchaseService: PurchaseService
    ) {
    }

    ngOnInit() {
        this.activatedRoute.url
            .pipe(skipWhile(() => this.router.url !== '/purchase/order/detail'))
            .subscribe(() => this.loadDatas());
        this.activatedRoute.paramMap.
            pipe(skipWhile(params => !params.has('id')))
            .subscribe(res => {
                this.orderId = parseInt(res.get('id'), 10);
                if (this.orderId) {
                    this.detailLoad();
                }
            });
    }

    loadDatas() {
        this.getSupplier();
        this.getPeople();
        this.getWarehouse();
        this.getArea();
    }

    addTr() {
        if (this.isAddTr) {
            this.isOnly = false;
            setTimeout(() => {
                this.isOnly = true;
            }, 100);
        }
        this.isAddTr = true;
    }

    childSave() {
        this.isAddTr = false;
        const childGood: any = {
            goodsNumber: this.newGoods.goodsNumber, goodsId: this.newGoods.goodsId,
            barCode: this.newGoods.barCode, manufactorNumber: this.newGoods.manufactorNumber,
            unit: this.newGoods.unit, flavorColor: this.newGoods.flavorColor,
            specificationsDimensions: this.newGoods.specificationsDimensions,
            amount: this.newGoods.amount, boxAmount: this.newGoods.boxAmount, price: this.newGoods.price,
            money: this.newGoods.money, taxRate: this.newGoods.taxRate,
            remarks: this.newGoods.remarks, boxBarCode: this.newGoods.boxBarCode, brandId: this.newGoods.brandId
        };
        childGood.isChange = true;
        this.listGoods.push(childGood);
        console.log('kkk', this.listGoods);
    }
    childDelete() {
        this.isAddTr = false;
    }
    /**
* order查询商品详情
*/
    detailLoad() {
        this.loading = true;
        this.purchaseService.getDetail(this.orderId)
            .subscribe({
                next: res => {
                    this.newList = res.datas;
                    this.listGoods = res.datas.goodsMsg;
                    this.supplierId = res.datas.supplierId;
                    this.listGoods.forEach(it => it.isChange = true);
                },
                complete: () => this.loading = false
            });
    }
    /**
* 供应商下拉选择
*/
    getSupplier() {
        this.purchaseService.supplierList()
            .subscribe({
                next: res => {
                    this.supplier = res.datas;
                },
            });
    }
    /**
* 人员下拉选择
*/
    getPeople() {
        this.purchaseService.peopleList()
            .subscribe({
                next: res => {
                    this.people = res.datas;
                },
            });
    }
    /**
* 仓库下拉选择
*/
    getWarehouse() {
        this.purchaseService.warehouse()
            .subscribe({
                next: res => {
                    this.warehouse = res.datas;
                },
            });
    }
    /**
* 区域下拉选择
*/
    getArea() {
        this.purchaseService.areaList()
            .subscribe({
                next: res => {
                    this.area = res.datas;
                },
            });
    }
    // warehouse
    /**
* 确定添加
*/
    confirmInsert(btn: any) {
        const addList = {
            orderDate: this.newList.orderDate, supplierId: this.newList.supplierId, balance: this.newList.balance,
            transportCompany: this.newList.transportCompany, estimatedArrivalDate: this.newList.estimatedArrivalDate,
            inWarehouseId: this.newList.inWarehouseId, buyerId: this.newList.buyerId, areaId: this.newList.areaId,
            volume: this.newList.volume, weight: this.newList.weight, applicantId: this.newList.applicantId,
            purchaseAmount: this.newList.purchaseAmount, purchaseBoxAmount: this.newList.purchaseBoxAmount,
            amountOfDocuments: this.newList.amountOfDocuments, wholeSingleDiscount: this.newList.wholeSingleDiscount,
            purchaseMode: this.newList.purchaseMode, supplierMobile: this.newList.supplierMobile,
            contractTask: this.newList.contractTask, annualTiredMining: this.newList.annualTiredMining,
            goods: this.listGoods
        };
        // const addList = {}; ${this.addList.supplierId}
        this.purchaseService.insertGoods(addList)
            .subscribe({
                next: res => {
                    this.toast.success('添加成功', `成功添加订单`);
                },
                complete: () => btn.dismiss()
            });
    }
    updateList(btn: any) {
        const updateList = {
            orderDate: this.newList.orderDate, supplierId: this.newList.supplierId, balance: this.newList.balance,
            transportCompany: this.newList.transportCompany, estimatedArrivalDate: this.newList.estimatedArrivalDate,
            inWarehouseId: this.newList.inWarehouseId, buyerId: this.newList.buyerId, areaId: this.newList.areaId,
            volume: this.newList.volume, weight: this.newList.weight, applicantId: this.newList.applicantId,
            purchaseAmount: this.newList.purchaseAmount, purchaseBoxAmount: this.newList.purchaseBoxAmount,
            amountOfDocuments: this.newList.amountOfDocuments, wholeSingleDiscount: this.newList.wholeSingleDiscount,
            purchaseMode: this.newList.purchaseMode, supplierMobile: this.newList.supplierMobile,
            contractTask: this.newList.contractTask, annualTiredMining: this.newList.annualTiredMining,
            goods: this.listGoods
        };
        this.purchaseService.updateGoods(updateList)
            .subscribe({
                next: res => {
                    this.toast.success('更新成功', `成功更新订单`);
                },
                complete: () => btn.dismiss()
            });
    }
    // confirmDelete(goods: Goods) {
    //     this.confirm.danger('删除确认', `您确认删除商品'${goods.goodsName}'吗？`)
    //         .pipe(switchMap<void, ApiData>(() => this.purchaseService.deleteGoods(goods.id)))
    //         .subscribe(() => {
    //             this.list.splice(this.list.indexOf(goods), 1);
    //             this.toast.success('删除成功', `成功删除商品'${goods.goodsName}`);
    //             this.loadDatas();
    //         });
    // }

}
